/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.PaginationUtil;
import com.ntb.common.SecuredAction;
import com.ntb.controllers.forms.SaleForm;
import com.ntb.entities.Flats;
import com.ntb.entities.Payments;
import com.ntb.entities.Sales;
import com.ntb.entities.StampDutyAndRegistration;
import com.ntb.models.FlatsDAO;
import com.ntb.models.PaymentsDAO;
import com.ntb.models.SalesDAO;
import com.ntb.models.impl.FlatsDAOImpl;
import com.ntb.models.impl.PaymentsDAOImpl;
import com.ntb.models.impl.SalesDAOImpl;
import com.ntb.models.impl.StampDutyAndRegistrationDAOImpl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class SaleAction extends SecuredAction {

    private List<String> errorMessages = new ArrayList();
    private List<String> successMessages = new ArrayList();

    @Override
    public ActionForward ntbExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        ActionForward forward = mapping.getInputForward();
        SaleForm saleForm = (SaleForm) form;
        SalesDAO saleDao = new SalesDAOImpl();
        String action = saleForm.getAction();

        errorMessages = new ArrayList();
        successMessages = new ArrayList();


        if ("selectFlat".equalsIgnoreCase(action)) {
            forward = selectFlat(request, saleForm, mapping);
        } else if ("reg".equalsIgnoreCase(action)) {
            StampDutyAndRegistration stamp = new StampDutyAndRegistrationDAOImpl().getLast();
            if (stamp == null) {
                errorMessages.add("The Stamp Duty And Registration is not available. You must add the Stamp Duty And Registration before registering.");
            } else {
                saleDao.updateToRegisterdSD(saleForm.getSaleID(), stamp.getSdCharge());
                successMessages.add("Registered successfully.");
            }
            forward = viewSale(saleDao, saleForm, request, mapping);
        } else if ("savePay".equalsIgnoreCase(action)) {
            PaymentsDAO paymentDao = new PaymentsDAOImpl();

            Payments payment = new Payments();

            payment.setPayID(saleForm.getPayID());

            int amountPaid = 0;
            try {
                amountPaid = Integer.parseInt(saleForm.getAmountPaid());
            } catch (Exception ex) {
            }
            payment.setAmountPaid(amountPaid);
            System.out.println("Amount" + amountPaid);

            payment.setDueDate(saleForm.getDueDate());

            payment.setSaleID(saleForm.getSaleID());

            if (saleForm.getPayID() > 0) {
                paymentDao.update(payment);
                successMessages.add("The payment has been saved.");
            } else {
                paymentDao.add(payment);
                successMessages.add("The payment has been added.");
            }
            forward = viewSale(saleDao, saleForm, request, mapping);
        } else if ("editPay".equalsIgnoreCase(action)) {
            // Show Edit Occupancy Permit Page

            PaymentsDAO paymentDao = new PaymentsDAOImpl();
            Payments payment = paymentDao.getRow(saleForm.getPayID());
            saleForm.setSaleID(saleForm.getSaleID());
            saleForm.setPayID(payment.getPayID());
            saleForm.setCreatedDate(payment.getCreatedDate());
            saleForm.setAmountDue(payment.getAmountDue());
            saleForm.setDueDate(payment.getDueDate());
            saleForm.setAmountPaid(payment.getAmountPaid() + "");

            Sales sales = saleDao.getRow(saleForm.getSaleID());

            int pay = sales.getTotalPayment();

            if (sales.getPaymentMode() == 1) {
                pay = (int) Math.floor(pay / 24);
            } else if (sales.getPaymentMode() == 2) {
                pay = (int) Math.floor(pay / 2);
            }
            saleForm.setPayment(pay);

            forward = mapping.findForward("paymentEdit");
        } else if ("addPay".equalsIgnoreCase(action)) {
            saleForm.setSaleID(saleForm.getSaleID());
            saleForm.setPayID(0);

            Sales sales = saleDao.getRow(saleForm.getSaleID());

            int pay = sales.getTotalPayment();

            if (sales.getPaymentMode() == 1) {
                pay = (int) Math.floor(pay / 24);
            } else if (sales.getPaymentMode() == 2) {
                pay = (int) Math.floor(pay / 2);
            }
            saleForm.setPayment(pay);

            forward = mapping.findForward("paymentCreate");
        } else if ("save".equalsIgnoreCase(action)) {
            // Save

            forward = updateSale(saleForm, saleDao, request, mapping);
            if (forward == null) {
                forward = viewSale(saleDao, saleForm, request, mapping);
            }
        } else if ("save & exit".equalsIgnoreCase(action)) {
            // Save & Back to list

            forward = updateSale(saleForm, saleDao, request, mapping);
            forward = forward == null ? mapping.findForward("saleListing") : forward;
        } else if ("edit".equalsIgnoreCase(action)) {
            // Show Edit Page

            forward = editSale(saleDao, saleForm, request, mapping);
        } else if (saleForm.getSaleID() > 0) {
            // Show Detail Page

            forward = viewSale(saleDao, saleForm, request, mapping);
        } else {
            // Show Add Page

            addSale(saleDao, saleForm, request, mapping);
        }

        request.setAttribute("errorMessages", errorMessages);
        request.setAttribute("successMessages", successMessages);

        return forward;
    }

    /**
     * Load Add Page
     * 
     * @param request
     * @param saleForm
     */
    private ActionForward addSale(SalesDAO saleDao, SaleForm saleForm, HttpServletRequest request, ActionMapping mapping) {
        FlatsDAO flatDao = new FlatsDAOImpl();
        if (flatDao.checkExist(saleForm.getFlatID())) {

            request.setAttribute("flat", flatDao.getRow(saleForm.getFlatID()));

            request.setAttribute("paymentModeList", saleDao.getPaymentModeList());
            saleForm.setSaleID(0);
            return mapping.getInputForward();
        } else {
            request.setAttribute("Please select a flat when add the sale.", this);
            return mapping.findForward("saleListing");
        }

    }

    /**
     * Load Edit Sale Page
     * 
     * @param saleDao
     * @param saleForm
     * @param request
     * @param mapping
     * @return
     */
    private ActionForward editSale(SalesDAO saleDao, SaleForm saleForm, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Sales sale = saleDao.getRow(saleForm.getSaleID());
        FlatsDAO flatDao = new FlatsDAOImpl();
        request.setAttribute("flat", flatDao.getRow(sale.getFlatID()));
        saleForm.setSaleID(sale.getSaleID());
        saleForm.setPaymentMode(sale.getPaymentMode());
        saleForm.setPaymentModeName(sale.getPaymentModeName());
        saleForm.setCustomerName(sale.getCustomerName());
        saleForm.setCustomerPhone(sale.getCustomerPhone());
        saleForm.setCustomerAddress(sale.getCustomerAddress());
        saleForm.setDescription(sale.getDescription());

        request.setAttribute("paymentModeList", saleDao.getPaymentModeList());

        forward = mapping.findForward("saleEdit");
        return forward;
    }

    /**
     * selectFlat
     * 
     * @param request
     * @param saleForm
     * @param mapping
     * @return
     */
    private ActionForward selectFlat(HttpServletRequest request, SaleForm saleForm, ActionMapping mapping) {
        ActionForward forward;

        FlatsDAO flatDAO = new FlatsDAOImpl();

        String baseUrl = request.getRequestURI() + "?action=selectFlat&amp;";

        String flatId = null;
        String flatName = null;
        String buildingId = null;
        String buildingName = null;
        int floorFrom = -1;
        int floorTo = -1;
        int areaFrom = -1;
        int areaTo = -1;

        int page = -1;

        flatId = saleForm.getId();
        flatId = "".equals(flatId) ? null : flatId;
        if (flatId != null) {
            baseUrl += "id=" + flatId + "&amp;";
        }

        flatName = saleForm.getName();
        flatName = "".equals(flatName) ? null : flatName;
        if (flatName != null) {
            baseUrl += "name=" + flatName + "&amp;";
        }

        buildingId = saleForm.getBuilding();
        buildingId = "".equals(buildingId) ? null : buildingId;
        if (buildingId != null) {
            buildingId += "building=" + buildingId + "&amp;";
        }

        buildingName = saleForm.getBuildingN();
        buildingName = "".equals(buildingName) ? null : buildingName;
        if (buildingName != null) {
            buildingName += "buildingN=" + buildingName + "&amp;";
        }

        try {
            floorFrom = Integer.parseInt(saleForm.getFloorF());
        } catch (Exception e) {
        }
        if (floorFrom > 0) {
            baseUrl += "floorF=" + floorFrom + "&amp;";
        } else {
            floorFrom = -1;
        }

        try {
            floorTo = Integer.parseInt(saleForm.getFloorT());
        } catch (Exception e) {
        }
        if (floorTo > 0) {
            baseUrl += "floorT=" + floorTo + "&amp;";
        } else {
            floorTo = -1;
        }

        try {
            areaFrom = Integer.parseInt(saleForm.getAreaF());
        } catch (Exception e) {
        }
        if (areaFrom > 0) {
            baseUrl += "areaF=" + areaFrom + "&amp;";
        } else {
            areaFrom = -1;
        }

        try {
            areaTo = Integer.parseInt(saleForm.getAreaT());
        } catch (Exception e) {
        }
        if (areaTo > 0) {
            baseUrl += "areaT=" + areaTo + "&amp;";
        } else {
            areaTo = -1;
        }

        try {
            int i = Integer.parseInt(request.getParameter("page"));
            page = i > 1 ? i : 1;
        } catch (Exception ex) {
        }

        Iterator<Flats> flatList = flatDAO.getList(flatId, flatName, buildingId, buildingName, floorFrom, floorTo, areaFrom, areaTo, page);
        request.setAttribute("flatList", flatList);

        PaginationUtil paginationUtil = new PaginationUtil();
        paginationUtil.setBaseUrl(baseUrl);
        paginationUtil.setNumPages(flatDAO.getPageCount(flatId, flatName, buildingId, buildingName, floorFrom, floorTo, areaFrom, areaTo));
        paginationUtil.setCurPage(page);
        request.setAttribute("pagination", paginationUtil.createLinks());
        forward = mapping.findForward("saleSelectFlat");
        return forward;
    }

    /**
     * Update Sale
     * 
     * @param saleForm
     * @param saleDao
     * @param mapping
     * @return
     */
    private ActionForward updateSale(SaleForm saleForm, SalesDAO saleDao, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Sales sale = new Sales();
        sale.setSaleID(saleForm.getSaleID());
        sale.setPaymentMode(saleForm.getPaymentMode());
        sale.setCustomerName(saleForm.getCustomerName());
        sale.setCustomerPhone(saleForm.getCustomerPhone());
        sale.setCustomerAddress(saleForm.getCustomerAddress());
        sale.setDescription(saleForm.getDescription());

        if (saleForm.getSaleID() > 0) {
            Sales temp = saleDao.getRow(saleForm.getSaleID());
            if (temp == null) {
                errorMessages.add("Sale not found!");
                forward = mapping.findForward("saleListing");
            } else {
                saleDao.update(sale);
                successMessages.add("The sale \"" + sale.getSaleID() + "\" has been saved.");
                return null;
            }
        } else {
            int flatID = saleForm.getFlatID();

            FlatsDAO flatsDao = new FlatsDAOImpl();

            if (!flatsDao.checkExist(flatID)) {
                errorMessages.add("The flat does not exits. Please check the flat and try again!");
                forward = addSale(saleDao, saleForm, request, mapping);

            } else {
                sale.setFlatID(flatID);

                saleDao.add(sale);
                successMessages.add("The new sale has been added.");
                forward = mapping.findForward("saleListing");
            }
        }
        return forward;
    }

    /**
     * Load Detail Page
     * 
     * @param saleDao
     * @param saleForm
     * @param request
     * @param mapping
     * @return
     */
    private ActionForward viewSale(SalesDAO saleDao, SaleForm saleForm, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Sales sale = saleDao.getRow(saleForm.getSaleID());
        request.setAttribute("sale", sale);

        FlatsDAO flatsDao = new FlatsDAOImpl();
        request.setAttribute("flat", flatsDao.getRow(sale.getFlatID()));

        PaymentsDAO paymentDao = new PaymentsDAOImpl();
        request.setAttribute("paymentList", paymentDao.getList(sale.getSaleID()));

        forward = mapping.findForward("saleDetail");
        return forward;
    }
}
